package handlers

import (
	"ticket/internal/db"
	"ticket/internal/db/model"
	"ticket/internal/schemas"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

type UserHandler struct{}

func RegisterUserRouter(group *gin.RouterGroup) {
	service := &UserHandler{}
	group.POST("/create", service.Create)
	group.GET("/list", service.List)
	group.GET("/get/:id", service.Get)
	group.GET("/info", service.Info)
	group.PUT("/update/:id", service.Update)
	group.DELETE("/delete/:id", service.Delete)
	group.PUT("/update-password", service.UpdatePassword)
	group.PUT("/reset-password", service.ResetPassword)
}

// Create godoc
// @Summary 创建用户
// @Description 创建用户
// @Security ApiKeyAuth
// @Tags 用户
// @ID /user/create
// @Accept json
// @Produce json
// @Param user body schemas.CreateUser true "用户信息"
// @Success 200 {object} schemas.Response{data=model.User} "用户创建成功"
// @Failure 1004 {object} schemas.Response{error=string} "参数错误"
// @Router /user/create [post]
func (s *UserHandler) Create(ctx *gin.Context) {
	params := &schemas.CreateUser{}
	if err := params.BindValidParam(ctx); err != nil {
		schemas.ResponseError(ctx, schemas.ParamInvalid, err)
		return
	}

	// 查询用户是否已经存在
	user := &model.User{
		UserName: params.Username,
		Password: params.Password,
		NickName: params.Nickname,
		Email:    params.Username,
	}
	if _, err := user.GetByUserName(db.GormDB, params.Username); err == nil {
		schemas.ResponseError(ctx, schemas.UserAlreadyExists, err)
		return
	}

	// 创建用户
	_, err := user.Create(db.GormDB)
	if err != nil {
		schemas.ResponseError(ctx, schemas.UserCreateFailed, err)
		return
	}

	schemas.ResponseSuccess(ctx, user)
}

// List godoc
// @Summary 获取用户列表
// @Description 获取用户列表
// @Security ApiKeyAuth
// @Tags 用户
// @ID /user/list
// @Accept json
// @Produce json
// @Success 200 {object} schemas.Response{data=[]model.User} "用户列表"
// @Failure 1004 {object} schemas.Response{error=string} "参数错误"
// @Router /user/list [get]
func (s *UserHandler) List(ctx *gin.Context) {
	user := &model.User{}
	users, err := user.List(db.GormDB)
	if err != nil {
		schemas.ResponseError(ctx, schemas.UserGetFailed, err)
		return
	}

	schemas.ResponseSuccess(ctx, users)
}

// Get godoc
// @Summary 获取用户信息
// @Description 获取用户信息
// @Security ApiKeyAuth
// @Tags 用户
// @ID /user/get/:id
// @Accept json
// @Produce json
// @Param id path int true "用户ID"
// @Success 200 {object} schemas.Response{data=model.User} "用户信息"
// @Failure 1004 {object} schemas.Response{error=string} "参数错误"
// @Router /user/get/{id} [get]
func (s *UserHandler) Get(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		schemas.ResponseError(ctx, schemas.ParamInvalid, errors.New("id不能为空"))
		return
	}
	user := &model.User{}
	user, err := user.GetByID(db.GormDB, id)
	if err != nil {
		schemas.ResponseError(ctx, schemas.UserGetFailed, err)
		return
	}
	schemas.ResponseSuccess(ctx, user)
}

// Info godoc
// @Summary 获取用户信息
// @Description 获取用户信息
// @Security ApiKeyAuth
// @Tags 用户
// @ID /user/info
// @Accept json
// @Produce json
// @Success 200 {object} schemas.Response{data=model.User} "用户信息"
// @Failure 1004 {object} schemas.Response{error=string} "参数错误"
// @Router /user/info [get]
func (s *UserHandler) Info(ctx *gin.Context) {
	session := sessions.Default(ctx)
	userId := session.Get("user_id")

	user := &model.User{}
	user, err := user.GetByID(db.GormDB, userId)
	if err != nil {
		schemas.ResponseError(ctx, schemas.UserNotExist, err)
		return
	}
	schemas.ResponseSuccess(ctx, user)
}

// Update godoc
// @Summary 更新用户信息
// @Description 更新用户信息
// @Security ApiKeyAuth
// @Tags 用户
// @ID /user/update/:id
// @Accept json
// @Produce json
// @Param id path int true "用户ID"
// @Param user body schemas.UpdateUser true "用户信息"
// @Success 200 {object} schemas.Response{data=model.User} "用户更新成功"
// @Failure 1004 {object} schemas.Response{error=string} "参数错误"
// @Router /user/update/{id} [put]
func (s *UserHandler) Update(ctx *gin.Context) {
	params := &schemas.UpdateUser{}
	if err := params.BindValidParam(ctx); err != nil {
		schemas.ResponseError(ctx, schemas.ParamInvalid, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		schemas.ResponseError(ctx, schemas.ParamInvalid, errors.New("id不能为空"))
		return
	}

	user := &model.User{}
	user, err := user.GetByID(db.GormDB, id)
	if err != nil {
		schemas.ResponseError(ctx, schemas.UserGetFailed, err)
		return
	}

	user.UserName = params.Username
	user.NickName = params.Nickname

	if err := user.Update(db.GormDB); err != nil {
		schemas.ResponseError(ctx, schemas.UserUpdateFailed, err)
		return
	}

	schemas.ResponseSuccess(ctx, user)
}

// Delete godoc
// @Summary 删除用户
// @Description 删除用户
// @Tags 用户
// @ID /user/delete/:id
// @Accept json
// @Produce json
// @Param id path int true "用户ID"
// @Success 200 {object} schemas.Response{data=string} "用户删除成功"
// @Failure 1004 {object} schemas.Response{error=string} "参数错误"
// @Router /user/delete/{id} [delete]
func (s *UserHandler) Delete(ctx *gin.Context) {
	id := ctx.Param("id")
	if id == "" {
		schemas.ResponseError(ctx, schemas.ParamInvalid, errors.New("id不能为空"))
		return
	}

	user := &model.User{}
	if err := user.Delete(db.GormDB, id); err != nil {
		schemas.ResponseError(ctx, schemas.UserDeleteFailed, err)
		return
	}

	schemas.ResponseSuccess(ctx, "用户删除成功")
}

// UpdatePassword godoc
// @Summary 更新用户密码
// @Description 更新用户密码
// @Security ApiKeyAuth
// @Tags 用户
// @ID /user/update-password
// @Accept json
// @Produce json
// @Param user body schemas.UpdateUserPassword true "用户密码信息"
// @Success 200 {object} schemas.Response{data=string} "用户密码更新成功"
// @Failure 1004 {object} schemas.Response{error=string} "参数错误"
// @Router /user/update-password [put]
func (s *UserHandler) UpdatePassword(ctx *gin.Context) {
	params := &schemas.UpdateUserPassword{}
	if err := params.BindValidParam(ctx); err != nil {
		schemas.ResponseError(ctx, schemas.ParamInvalid, err)
		return
	}

	id := ctx.GetUint("user_id")
	user := &model.User{}
	user, err := user.GetByID(db.GormDB, id)
	if err != nil {
		schemas.ResponseError(ctx, schemas.UserGetFailed, err)
		return
	}

	if !user.CheckPassword(params.OldPassword) {
		schemas.ResponseError(ctx, schemas.UserPasswordError, errors.New("旧密码错误"))
		return
	}

	if params.Password != params.Confirm {
		schemas.ResponseError(ctx, schemas.PasswordNotMatch, errors.New("两次输入的密码不一致"))
		return
	}

	if _, err := user.UpdatePassword(db.GormDB, params.Password); err != nil {
		schemas.ResponseError(ctx, schemas.UserUpdateFailed, err)
		return
	}

	schemas.ResponseSuccess(ctx, "用户密码更新成功")
}

// ResetPassword godoc
// @Summary 重置用户密码
// @Description 重置用户密码
// @Tags 用户
// @ID /user/reset-password
// @Accept json
// @Produce json
// @Param user body schemas.ResetPassword true "重置密码信息"
// @Success 200 {object} schemas.Response{data=string} "用户密码重置成功"
// @Failure 1004 {object} schemas.Response{error=string} "参数错误"
// @Router /user/reset-password [put]
func (s *UserHandler) ResetPassword(ctx *gin.Context) {
	params := &schemas.ResetPassword{}
	if err := params.BindValidParam(ctx); err != nil {
		schemas.ResponseError(ctx, schemas.ParamInvalid, err)
		return
	}

	user := &model.User{}
	user, err := user.GetByID(db.GormDB, params.ID)
	if err != nil {
		schemas.ResponseError(ctx, schemas.UserGetFailed, err)
		return
	}

	if params.Password != params.Confirm {
		schemas.ResponseError(ctx, schemas.PasswordNotMatch, errors.New("两次输入的密码不一致"))
		return
	}

	if _, err := user.UpdatePassword(db.GormDB, params.Password); err != nil {
		schemas.ResponseError(ctx, schemas.UserUpdateFailed, err)
		return
	}

	schemas.ResponseSuccess(ctx, "用户密码重置成功")
}
